package com.yuanxiao.service;

import com.yuanxiao.model.RpcRequest;
import com.yuanxiao.springUtils.AppUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.EventExecutorGroup;

import java.lang.reflect.Method;

public class UserServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //判断是否符合约定,符合则调用本地方法,返回数据
        //msg:UserService#sayHello#are you ok?
      /*  if(msg.toString().startsWith("UserService")){

           // Class<?> aClass = Class.forName("com.yuanxiao.service.UserService");
           // UserServiceImpl userService = (UserServiceImpl) aClass.newInstance();
            UserServiceImpl userService = new UserServiceImpl();
            String s = userService.sayHello(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
            ctx.writeAndFlush(s);
        }*/
      //接收参数改为Rpcrequset
        if (msg instanceof RpcRequest){
            RpcRequest rpcRequest = (RpcRequest)msg;
            String className = rpcRequest.getClassName();
            String methodName = rpcRequest.getMethodName();
            Object[] parameters = rpcRequest.getParameters();
            Class<?>[] parameterTypes = rpcRequest.getParameterTypes();
            String requestId = rpcRequest.getRequestId();

            Class<?> aClass = Class.forName(className);
            Method method = aClass.getMethod(methodName, parameterTypes);
            String invoke = (String)method.invoke(AppUtil.getObject(aClass), parameters);
            ctx.writeAndFlush(invoke);
        }

    }

}
